<template>
  <Form :form="form">
    <SchemaField :schema="schema" />
    <Submit @submit="onSubmit">提交</Submit>
  </Form>
</template>

<script lang="ts" setup>
definePage({
  name: 'form',
  meta: {
    requiresAuth: true // 定义元数据，标记该路由需要认证
  }
})

import { createForm, onFieldValueChange } from '@formily/core'
import { createSchemaField } from '@formily/vue'
import { Form, FormItem, Checkbox, Submit, Input, Password } from '@formily/element-plus'

const schema = {
  type: 'object',
  properties: {
    layout: {
      type: 'void',
      'x-component': 'FormLayout',
      'x-component-props': {
        labelCol: 6,
        wrapperCol: 10,
        layout: 'vertical'
      },
      properties: {
        checkbox: {
          required: true,
          type: 'number',
          title: '是否确认',
          'x-decorator': 'FormItem',
          'x-component': 'Checkbox'
        },
        checkboxGroup: {
          type: 'array',
          title: '复选',
          'x-decorator': 'FormItem',
          'x-component': 'Checkbox.Group',
          enum: [
            {
              label: '选项1',
              value: 1
            },
            {
              label: '选项2',
              value: 2
            }
          ]
        },
        input: {
          type: 'string',
          title: '输入框',
          required: true,
          'x-decorator': 'FormItem',
          'x-component': 'Input',
          'x-component-props': {}
        },
        password: {
          type: 'string',
          title: '密码',
          required: true,
          'x-decorator': 'FormItem',
          'x-component': 'Password',
          'x-component-props': {
            // checkStrength: true
          },
          'x-reactions': [
            {
              dependencies: ['.input'],
              fulfill: {
                state: {
                  selfErrors:
                    '{{$deps[0] && $self.value && $self.value !== $deps[0] ? "确认密码不匹配" : ""}}'
                }
              }
            }
          ]
        }
      }
    }
  }
}

const form = createForm({
  effects() {
    // 当复选框状态改变时
    onFieldValueChange('checkbox', (field) => {
      // 如果选中，设置输入框的值为 "已确认"
      if (field.value) {
        // 修复TypeScript错误，使用可选链和类型断言
        const inputField = field.query('input').take() as any
        inputField?.setValue?.('已确认')
      } else {
        // 如果未选中，清空输入框
        const inputField = field.query('input').take() as any
        inputField?.setValue?.('')
      }
    })

    // 监听输入框字段
    onFieldValueChange('input', (field) => {
      // 如果输入框有值，自动选中复选框
      const checkboxField = field.query('checkbox').take() as any
      checkboxField?.setValue?.(!!field.value)
    })
  }
})

const { SchemaField } = createSchemaField({
  components: {
    FormItem,
    Checkbox,
    Input,
    Password
  }
})

const onSubmit = (value: any) => {
  console.log(value)
}
</script>
